from typing import cast

from src.application.common.exceptions import MappingError
from src.application.user.dto import UserDTO
from src.domain.user import value_objects as vo
from src.domain.user.aggregates import UserAggregate
from src.infrastructure.db import models

from .allowed_ip import convert_allowed_ip_entity_to_db_model


def convert_user_entity_to_db_model(user: UserAggregate) -> models.User:
    allowed_ips = [convert_allowed_ip_entity_to_db_model(allowed_ip) for allowed_ip in user.allowed_ips]
    return models.User(
        id=user.id,
        telegram_id=user.tg_id.value,
        username=cast(str, user.username),
        balance=user.balance,
        email=cast(str, user.email),
        allowed_ips=allowed_ips,
        is_registered=user.is_registered,
    )


def convert_db_model_to_user_entity(user: models.User) -> UserAggregate:
    return UserAggregate(
        id=vo.UserId(user.id),
        tg_id=vo.TelegramUserId(user.telegram_id),
        username=user.username,
        email=user.email,
        is_registered=user.is_registered,
    )


def convert_db_model_to_active_user_dto(user: models.User) -> UserDTO:
    return UserDTO(
        id=user.id,
        tg_id=user.telegram_id,
        username=cast(str, user.username),
        email=user.email,
        is_registered=user.is_registered,
        was_registered=user.was_registered,
        # hashed_password=user.hashed_password,
        # salt=user.salt,
    )


def convert_db_model_to_user_dto(user: models.User) -> UserDTO:
    match user:
        case models.User(is_active=True):  # TODO Заменить
            return convert_db_model_to_active_user_dto(user)
        # case models.User(is_active=True):
        #     return convert_db_model_to_deleted_user_dto(user)
        case _:
            raise MappingError(f"User {user} is invalid")
